﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using AT_UHF_NET;
using ceTerm.OverProduction;
using System.Drawing;

namespace ceTerm
{
    public partial class ReadWriteRFID : XForm
    {
        int oldRollId = -1;        
        int yeniId;

        public ReadWriteRFID(int oldRollId,string article,string brand,Image img)
        {
            this.oldRollId = oldRollId;

            InitializeComponent();

            pnlSinyalGucu.Visible = false;
            this.WindowState = FormWindowState.Maximized;
            this.KeyPreview = true;

            lblRollId.Text = oldRollId.ToString();
            lblBrand.Text = brand;
             lblArtikel.Text = article;
            
            pb.Image = img;
            txtMetraj.Focus();

            Terminal.SetActivatedForm(this);
        }

        private void ShowInfo(string info)
        {
            lblStatus.Text = info;
        }

        //Read Events
        public override void GetReply(string Reply)
        {
            switch (action)
            {
                case Action.Write:  //timer_tick ten buraya kaydırıldı!
                    action = Action.IDLE;
                    if (tags.Count == 0)
                    {
                        Terminal.PlayFail();
                        Start();
                        ShowInfo("Ortamda RFID etiket yok, yazılamadı !");
                    }
                    else if (tags.Count > 1)
                    {                        
                        tags.Clear();
                        Terminal.PlayFail();
                        Start();
                        ShowInfo("Ortamda birden fazla (" + tags.Count + 1 + ") RFID etiket var, yazılamadı !");
                    }
                    else
                        WriteTag(yeniId);

                    break;

                default:
                    //ShowInfo(Reply);
                    break;
            }
        }

        List<int> tags = new List<int>();
        //On RFID Read
        bool isWorking = false;
        public override void GetAccessEPC(string EPC)
        {
            if (isWorking)
                return;

            string[] temp = EPC.Split(",".ToCharArray());
            EPC = temp[0].Substring(4, temp[0].Length - 4);
            int EPCint = intParse(EPC);

            if (tags.IndexOf(EPCint) < 0)
                tags.Add(EPCint);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            timer.Enabled = false;
            isWorking = true;
            Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.ACCESS_EPC, false);

            action = Action.Write;
            Terminal.RFID.Stop();   //GetReply ı çağırır
            isWorking = false;
        }

        private void Start()
        {
            tags.Clear();
            Terminal.StartRFID();
            Terminal.SetActivatedForm(this);
            Terminal.RFID.SET_PowerControl(0);
            ShowInfo("");
            isWorking = false;
        }
        
        private void WriteTag(int RollId)
        {
            try
            {
                Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, true);
                Terminal.RFID.SET_PowerControl(0);   //GetReply ı çağırır

                AccessResult ar = Terminal.WriteRFID2(RollId);
                if (ar == AccessResult.OK)
                {
                    string ret = Terminal.RFID.GET_LAST_ERROR();
                    if (ret == "Success")
                    {
                        Main.ceWS.OPUpdRfid(Main.Password,yeniId);
                        ShowInfo("RFID etikete yazıldı.");
                        Terminal.PlaySuccess();

                        Message m = new Message();
                        m.lblId.Text = yeniId.ToString();
                        m.ShowDialog();
                        this.Close();
                    }
                    else
                    {
                        ShowInfo("Etikete yazılamadı. (" + ret + ")");
                        Terminal.PlayFail();
                    }
                }
                else
                {
                    ShowInfo("Etikete yazılamadı. (" + ar.ToString() + ")");
                    Terminal.PlayFail();
                }
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
            finally
            {                
                Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, false);
                Start();
            }

        }
        bool yeniIdAdded = false;
        private void btnKaydet_Click(object sender, EventArgs e)
        {
            decimal qty = 0;
            decimal en = 0;
            try
            {
                qty = decimal.Parse(txtMetraj.Text);
                en  = decimal.Parse(txtEn.Text);
            }
            catch
            {
                ShowInfo("Metreleri doğru yazın.");
                tags.Clear();
                Terminal.PlayFail();
                return;
            }
            if (!(qty > 0) || !(en > 0) )
            {
                ShowInfo("Metrajı doğru yazın.");
                tags.Clear();
                Terminal.PlayFail();
                return;
            }

            if (!yeniIdAdded)
            {
                yeniId = Main.ceWS.OPInsRoll(Main.Password,Settings.TerminalId, oldRollId, qty, en);
                yeniIdAdded = true;
            }
            
              
            //Terminal.StartRFID();

            //Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.ACCESS_EPC, true);
            //Terminal.RFID.SET_PowerControl((uint)Settings.Power.Yazma/*OkumaMax*/);   //GetReply ı çağırır

            //timer.Interval = (int)Settings.OkumaSuresiMs;
            timer.Enabled = true;
        }
    }
}